package com.ktwlsoft.archivemanage.domain.business.repositoryService;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import com.ktwlsoft.archivemanage.domain.dao.entity.Imgs;
import com.ktwlsoft.archivemanage.domain.dao.repository.IImgsMapper;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.exception.BusinessException;
import com.ktwlsoft.archivemanage.service.img.FileStorageService;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * imgs--图片业务层接口实现类
 *
 * @author zhuhe on 2019-10-24 14:19:41
 * @version 1.0
 */
@Service
@RequiredArgsConstructor
public class ImgsService {

	private final IImgsMapper imgsMapper;

	private final FileStorageService fileStorageService;

	/**
	 * 查询分页 on 2019-10-24 14:19:41
	 * @param pn 第几页
	 * @param pageSize 每页多少条
	 * @param imgs imgs
	 * @return PageInfo<Imgs>
	 */
	public PageInfo<Imgs> findPage(int pn, int pageSize, Imgs imgs) {
		PageHelper.startPage(pn,pageSize);
		PageInfo<Imgs> pageInfo = new PageInfo<Imgs>(imgsMapper.findList(imgs));
		return pageInfo;
	}

	/**
	 * 查询集合 on 2019-10-24 14:19:41
	 * @param imgs imgs
	 * @return List<Imgs>
	 */
	public List<Imgs> findList(Imgs imgs) {
		return imgsMapper.findList(imgs);
	}

	/**
	 * 根据ID查询信息 on 2019-10-24 14:19:41
	 * @param id	主键
	 * @return Imgs
	 */
	public Imgs getById(Long id){
		return imgsMapper.getById(id);
	}

	/**
	 * 新增 on 2019-10-24 14:19:41
	 * @param imgs imgs
	 * @return int
	 */
	public int insert(Imgs imgs){
		return imgsMapper.insert(imgs);
	}

	/**
	 * 批量插入 on 2019-04-23 10:57:02
	 * @param list list
	 * @return int
	 */
	public int manyInsert(List<Imgs> list){
		return imgsMapper.manyInsert(list);
	}

	/**
	 * 新增图片 on 2019/11/11 10:10
	 *
	 * @param businessId businessId
	 * @param businessType businessType
	 * @param url url
	 * @return Long Long
	 */
	public Long save(Long businessId,String businessType,String url){
		Imgs imgs = new Imgs();
		//id
		imgs.setId(SnowFlake.getNextId());
		//业务id
		imgs.setBusinessId(businessId);
		//业务类型
		imgs.setBusinessType(businessType);
		//相对地址
		imgs.setUrl(url);
		//名称
		String fileName = url.substring(url.lastIndexOf(File.separator)+1,url.length());
		imgs.setFileName(fileName);
		//后缀
		String[] strings = fileName.length() > 0?fileName.split("\\."):null;
		imgs.setSuffix(strings != null?strings[strings.length - 1]:"");
		//大小
		imgs.setSize(0L);
		//创建人
		imgs.setCreator(null);
		//创建人id
		imgs.setCreatorId(null);
		//创建时间
		imgs.setCreatedAt(new Date());
		//更新时间
		imgs.setUpdateAt(new Date());
		try {
			int imgResult = insert(imgs);
			if(imgResult<=0){
				throw new BusinessException("未能正常添加图片地址，img::"+imgs.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return 0L;
		}
		return imgs.getId();
	}

	/**
	 * 批量新增图片 on 2019/11/11 10:10
	 *
	 * @param businessId businessId
	 * @param businessType businessType
	 * @param imgss imgss
	 * @return Long Long
	 */
	public void manySave(Long businessId,String businessType,List<Imgs> imgss){
		if(imgss == null || imgss.size() <= 0){
			return ;
		}
		for(Imgs imgs:imgss){
			//id
			imgs.setId(SnowFlake.getNextId());
			//业务id
			imgs.setBusinessId(businessId);
			//业务类型
			imgs.setBusinessType(businessType);
			//名称
			imgs.setFileName(imgs.getFileName());
			//后缀
			imgs.setSuffix(imgs.getSuffix());
			//大小
			imgs.setSize(imgs.getSize());
			//创建人
			imgs.setCreator(null);
			//创建人id
			imgs.setCreatorId(null);
			//创建时间
			imgs.setCreatedAt(new Date());
			//更新时间
			imgs.setUpdateAt(new Date());
		}
		try {
			manyInsert(imgss);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 修改 on 2019-10-24 14:19:41
	 * @param imgs imgs
	 * @return int
	 */
	public int update(Imgs imgs){
		return imgsMapper.update(imgs);
	}

	/**
	 * 根据id集合批量删除信息 on 2019-10-24 14:19:41
	 * @param imgsArr	主键编号集合
	 * @return int
	 */
	public int deleteByIds(List<Long> imgsArr){
		return imgsMapper.deleteByIds(imgsArr);
	}

	/**
	 * 根据id删除信息 on 2019-10-24 14:19:41
	 * @param id id
	 * @return int
	 */
	public int deleteById(Long id){
		return imgsMapper.deleteById(id);
	}

	/**
	 * 根据业务id与业务类型查询数据 on 2019/10/24 14:37
	 *
	 * @param imgs imgs
	 * @return int int
	 */
	public List<Imgs> getByBusinessIdAndBusinessType(Imgs imgs){
		return imgsMapper.getByBusinessIdAndBusinessType(imgs);
	}

	/**
	 * 根据业务编号删除图片
	 * @param businessId
	 * @return int
	 */
	public int deleteImagesByBusinessId(Long businessId){
		return imgsMapper.deleteImagesByBusinessId(businessId);
	}

	/**
	 * 根据业务编号和业务类型删除图片
	 * @param businessId
	 * @param businessType
	 * @return int
	 */
	public int deleteByBusinessIdAndBusinessType(Long businessId,String businessType){
		Imgs imgs = new Imgs();
		imgs.setBusinessId(businessId);
		imgs.setBusinessType(businessType);
		return imgsMapper.deleteByBusinessIdAndBusinessType(imgs);
	}

	/**
	 * 更新图片数据
	 * @param imgs
	 * @return int
	 */
	public int updateImagesData(Imgs imgs){
		return imgsMapper.update(imgs);
	}

	public List<Imgs> findImagesByBusinessId(Long businessId){
		return imgsMapper.findImagesListByBusinessId(businessId);
	}

	/**
	 * 文件下载 on 2019/12/30 17:33
	 *
	 * @param id id
	 * @param request  request
	 * @return ResponseEntity<?>
	 */
	public ResponseEntity<?> download(Long id, HttpServletRequest request) {
		Imgs imgs = imgsMapper.getById(id);
		if (imgs == null) {
			return ResponseEntity.ok(Result.body(null, ResultType.CHECK_ERROR).withMessage("该文件不存在"));
		}
		Resource resource = null;
		String contentType = null;
		try {
			resource = fileStorageService.loadFileAsResource(imgs.getUrl());
			System.out.println("文件url:" + resource.getURL());
			if (!resource.exists()) {
				return ResponseEntity.ok(Result.body(null, ResultType.CHECK_ERROR).withMessage("获取不到该文件"));
			}
			contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.ok(Result.body(null, ResultType.BUSINESS_SUCCESS));
		}
		if (contentType == null) {
			contentType = "application/octet-stream";
		}
		// 名字转换
		String[] strArr = resource.getFilename().split("\\.");
		String fileNamePrefix = strArr[0];
		String fileNameSuffix = strArr[1];
		String finalFileName = null;
		try {
			finalFileName = URLDecoder.decode(fileNamePrefix, "UTF-8") + "." + fileNameSuffix;
		} catch (UnsupportedEncodingException e) {
			System.out.println("文件名字转换异常");
			System.out.println(e.getMessage());
		}
		return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
				.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"")
				.body(resource);
	}
}
